import { page } from '@/apis/InterviewQuestions'
import { usePagination } from '@/hooks/usePagination'
import type { InterviewQuestions } from '@/models/InterviewQuestions/InterviewQuestions'
import type { InterviewQuestionsSearch } from '@/models/InterviewQuestions/InterviewQuestionsSearch'
import type { PageInfo } from '@/models/Pagination/PageInfo'
import { notification, type TableProps } from 'ant-design-vue'
import { computed, ref } from 'vue'

export function useInterviewQuestionsListPageData(
  entityName: string,
  formState: Partial<InterviewQuestionsSearch>,
  resetFormState: () => void,
) {
  const tableData = ref<InterviewQuestions[]>([])
  const pagination = usePagination()
  const pagePreTotal = computed(() => {
    if (pagination.current <= 1) return 0
    return (pagination.current - 1) * pagination.pageSize
  })
  function currentRowIndex(index: number) {
    return pagePreTotal.value + index + 1
  }
  const loading = ref(false)

  async function getPageData() {
    if (loading.value) return
    loading.value = true
    try {
      const res = await page({
        page: pagination.current,
        size: pagination.pageSize,
        ...formState,
      })
      if (res.data) {
        const pageData: PageInfo<InterviewQuestions> = res.data
        tableData.value = pageData.list
        if (res.data.pageNum) {
          pagination.current = ~~res.data.pageNum as number
        }
        if (res.data.total) {
          pagination.total = ~~res.data.total as number
        }
      } else {
        tableData.value = []
        notification.error({ message: `分页获取${entityName}失败!` })
      }
    } catch (error) {
      tableData.value = []
      notification.error({ message: `分页获取${entityName}失败!` })
    }
    loading.value = false
  }

  function initSearch() {
    resetFormState()
    onClickSearch()
  }

  initSearch()

  const onChangeTable: TableProps['onChange'] = function (pageData) {
    if (pageData.pageSize && pagination.pageSize !== pageData.pageSize) {
      pagination.current = 1
      pagination.pageSize = pageData.pageSize
    }
    if (pageData.current && pagination.current !== pageData.current) {
      pagination.current = pageData.current
    }
    getPageData()
  }

  function onClickSearch() {
    pagination.current = 1
    getPageData()
  }

  return {
    tableData,
    pagination,
    currentRowIndex,
    loading,
    getPageData,
    onClickSearch,
    onClickSearchReset: initSearch,
    onChangeTable,
  }
}
